import Dialog from '../../../../miniprogram_npm/@vant/weapp/dialog/dialog';
import Toast from '../../../../miniprogram_npm/@vant/weapp/toast/toast';
import * as Storage from '../../../../utils/storage';
import subPub from '../../../../utils/subPub';
import { formatDateString, initLocationPersmiss } from '../../../../utils/util';
const $api = require('../../../../request/api').API;

const app = getApp();
// 获取去年今天的日期
const date = new Date();
const lastYear = new Date(date.getFullYear() - 1 + '-' + (date.getMonth() + 1) + '-' + date.getDate()).getTime();
Page({
  data: {
    beeperId: '',
    dataList: [],
    //分页相关
    pageNo: 1,
    pageSize: 10,
    totalPage: 1,
    mainFlag: 0,
    showFilter: false,
    showDate: false,
    currentDate: '',
    beginDate: '',
    endDate: '',
    dateTitle: '结束时间',
    maxDate: new Date().getTime(),
    minDate: lastYear,

    type: 1, //表示是开始时间还是介绍时间
    // 格式化时间
    formatDate: function (type, value) {
      if (type === 'year') {
        return `${value}年`;
      }
      if (type === 'month') {
        return `${value}月`;
      }
      if (type === 'day') {
        return `${value}日`;
      }
      return value;
    },
    btnId: '',
    btnServerClassifyIds: '',
    queryType: '',
    // 选择支付弹框
    showPayDialog: false,
    // 支付方式
    payType: 1,
    // 选中的订单编号
    orderNo: '',
    // 加载
    loading: false
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function ({ beeperId }) {
    // 初始化当月的beginDate与endDate
    const date = new Date();
    const year = date.getFullYear();
    const month = date.getMonth();
    const days = new Date(year, month + 1, 0).getDate();
    const begin = new Date(year, month, 1);
    let beginDate = formatDateString(begin, 'yyyy-MM-dd');
    let endDate = formatDateString(new Date(year, month, days), 'yyyy-MM-dd');
    this.beginDateStamp = begin.getTime();
    this.setData({ beeperId, beginDate, endDate });
    this.getData();

    // 监听详情页面订单状态改变
    this.orderModifyStateId = subPub.on('orderModifyState', ({ orderId, orderState, payState }) => {
      const { dataList } = this.data;
      const index = dataList.findIndex(item => item.orderId == orderId);
      if (index == -1) return;
      const target = dataList[index];
      Object.assign(target, { orderState, payState });
      const prop = `dataList[${index}]`;
      this.setData({
        [prop]: target
      });
    });
  },
  onReady() {},
  onShow: async function () {},
  async exportOrder() {
    const { beeperId, beginDate, endDate } = this.data;

    await Dialog.confirm({
      title: '提示',
      message: '确定导出？'
    });
    Toast.loading({
      message: '订单导出中',
      forbidClick: true,
      mask: true
    });
    const params = {
      beeperId,
      beginDate: beginDate + ' 00:00:00',
      endDate: endDate + ' 23:59:59'
    };
    //
    let res = await $api.getOrderExportUrl(params);
    wx.downloadFile({
      // 示例 url，并非真实存在
      url: res.data.data,
      success: function (res) {
        wx.openDocument({
          showMenu: true,
          filePath: res.tempFilePath
        });
      }
    });
    Toast.success('导出成功');
  },
  // 搜索
  handleSearch() {
    this.setData({
      pageNo: 1
    });
    this.getData();
  },
  // 显示时间选择弹框
  showDatePopup(e) {
    this.startDateFlag = e ? true : false;
    let { minDate } = this.data;
    let currentDate = '';
    if (this.startDateFlag) {
      minDate = lastYear;
      // maxDate = new Date().getTime()
      if (this.beginDateStamp) {
        currentDate = this.beginDateStamp;
      } else {
        currentDate = new Date().getTime();
      }
    } else if (!this.startDateFlag) {
      // const date = new Date(this.beginDateStamp)
      // const year = date.getFullYear()
      // const month = date.getMonth()
      minDate = this.beginDateStamp;
      // const days = new Date(year,month+1,0).getDate()
      // maxDate = new Date(year,month,days).getTime()
    }
    this.setData({
      showDate: true,
      currentDate,
      // maxDate,
      minDate,
      dateTitle: this.startDateFlag ? '开始日期' : '结束日期'
    });
  },
  closeDatePopup() {
    this.setData({
      showDate: false
    });
  },
  // 日期改变
  dateChange(e) {
    this.setData({
      currentDate: e.detail
    });
  },
  // 确认时间
  confirmDate(e) {
    this.setData({
      currentDate: e.detail
    });
    if (this.startDateFlag) {
      this.beginDateStamp = e.detail;
      this.beginDate = formatDateString(e.detail, 'yyyy-MM-dd');
      this.showDatePopup();
    } else {
      this.endDateStamp = e.detail;
      this.setData({
        beginDate: this.beginDate,
        endDate: formatDateString(e.detail, 'yyyy-MM-dd')
      });
      this.closeDatePopup();
    }
  },
  // 获取列表数据
  async getData() {
    const { beginDate, endDate, pageNo, pageSize, beeperId, dataList } = this.data;
    let params = {
      pageNo,
      pageSize,
      beginDate,
      endDate,
      beeperId
    };
    this.setData({
      loading: true
    });
    try {
      const res = await $api.orderList(params);
      let { list, totalPage } = res.data.data;
      this.setData({
        dataList: pageNo == 1 ? list : dataList.concat(list),
        totalPage,
        loading: false
      });
      // 置顶
      wx.pageScrollTo({
        scrollTop: 0,
        duration: 0
      });
    } finally {
      this.setData({
        loading: false
      });
    }
  },
  // 拨打电话
  callPhone(e) {
    let phone = e.currentTarget.dataset.phone;
    wx.makePhoneCall({
      phoneNumber: phone, //仅为示例，并非真实的电话号码
      success: function () {
        console.log('拨打电话成功！');
      },
      fail: function () {
        console.log('拨打电话失败！');
      }
    });
  },
  // 去评价
  toEvaluate(e) {
    wx.navigateTo({
      url: '/subcontract/order/pages/evaluate/index?orderId=' + e.currentTarget.dataset.id
    });
  },
  // 结果查询
  async queryResult(e) {
    let res = await $api.listKlabReportUrl({ orderId: e.currentTarget.dataset.item.orderId });
    res = res.data.data || '';
    if (!res) {
      Toast.fail('暂未查询到结果');
      return;
    }
    wx.downloadFile({
      url: res,
      success: res2 => {
        wx.openDocument({
          filePath: res2.tempFilePath,
          fileType: 'pdf',
          showMenu: true
        });
      },
      fail(err) {
        console.log(err);
      }
    });
  },
  // 再来一单
  anotherOrder(e) {
    let item = e.currentTarget.dataset.item;
    let shopCartData = [];
    $api.againOrderInfo({ orderId: item.orderId }).then(res => {
      let data = res.data.data;
      data.goodsList.forEach(item2 => {
        shopCartData.push({
          ruleId: data.ruleId,
          businessId: data.businessId,
          businessName: data.businessName,
          id: item2.beeperBtnId,
          nums: item2.nums,
          salePrice: item2.salePrice,
          packageFee: item2.packageFee,
          mainImage: item2.images,
          fastFlag: item2.fastFlag,
          goodsId: item2.goodsId,
          serverId: item2.serverId,
          thirdClassifyId: item2.thirdClassifyId,
          variantId: item2.variantId,
          name: item2.name,
          goodsType: item2.goodsType,
          specVal: item2.strSpecVal,
          relationVariantId: item2.variantIds || [],
          relationNames:
            item2.oGRelations && item2.oGRelations.length ? item2.oGRelations.map(item => item.name).toString() : ''
        });
      });
      wx.setStorageSync('shopCartData', JSON.stringify(shopCartData));
      initLocationPersmiss().then(res => {
        app.globalData['btnList.beeperId'] = item.beeperId;
        app.globalData['btnList.latitude'] = res.location.lat;
        app.globalData['btnList.longitude'] = res.location.lng;
        app.globalData['btnList.btnId'] = data.btnId;
        app.globalData['btnList.btnServerClassifyIds'] = data.btnServerClassifyIds;
        app.globalData['btnList.queryType'] = data.queryType;
        wx.navigateTo({
          url: '/subcontract/home/pages/submitOrder/index?another=1'
        });
      });
    });
  },
  // 继续支付
  async continuePay(e) {
    let data = e.currentTarget.dataset.item;
    let mianFlag = this.data.mainFlag;
    if (data.beeperId) {
      let res = await this.getBeeperBalance(data.beeperId);
      if (
        mianFlag &&
        data.goodsType != 3 &&
        ((data.payState == 1 && data.realAmount < res) || (data.payState == 4 && data.lastAmount < res))
      ) {
        this.setData({
          showPayDialog: true,
          orderNo: data.orderNo,
          payType: 1
        });
      } else {
        this.setData({
          payType: 2,
          orderNo: data.orderNo
        });
        this.confrimPay();
      }
    } else {
      this.setData({
        payType: 2,
        orderNo: data.orderNo
      });
      this.confrimPay();
    }
  },
  // 支付方式
  payChange(val) {
    let type = val.currentTarget.dataset.type;
    this.setData({
      payType: type
    });
  },
  // 确认支付
  confrimPay() {
    let payType = this.data.payType;
    let params = {
      orderNos: this.data.orderNo,
      openId: wx.getStorageSync(Storage.USER_OPEN_ID),
      payType: payType
    };
    if (payType == 1) {
      Toast.loading({
        message: '支付中',
        forbidClick: true,
        mask: true
      });
    }
    $api.scanToPayWaitOrder(params).then(res => {
      let data = res.data.data;
      if (payType == 1) {
        Toast.success({
          message: '支付成功',
          forbidClick: true,
          mask: true
        });
        setTimeout(() => {
          this.getData();
        }, 1000);
      } else if (payType == 2) {
        let _this = this;
        wx.requestPayment({
          timeStamp: data.timeStamp,
          nonceStr: data.nonceStr,
          package: data.package,
          signType: data.signType,
          paySign: data.paySign,
          success: res => {
            Toast.success({
              message: '支付成功',
              forbidClick: true
            });
            setTimeout(() => {
              _this.getData();
            }, 1000);
          },
          fail: err => {
            Toast.fail({
              message: '支付失败',
              forbidClick: true
            });
          },
          complete: res => {}
        });
      }
    });
  },
  // 查询余额
  async getBeeperBalance(beeperId) {
    let params = {
      id: beeperId
    };
    let res = await $api.getBeeperBalance(params);
    return res.data.data;
  },
  toDetail(e) {
    let id = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: '/subcontract/order/pages/details/index?orderId=' + id + '&mainFlag=' + this.data.mianFlag
    });
  },
  //刷新
  onRefresh() {
    //显示 loading 提示框。需主动调用 wx.hideLoading 才能关闭提示框
    wx.showLoading({
      title: '刷新中...'
    });
    this.setData({
      pageNo: 1
    });
    this.getData();

    setTimeout(() => {
      wx.showToast({
        title: '刷新成功'
      });
      wx.stopPullDownRefresh();
    }, 1000);
  },
  // 通过id获取索引
  getIndexById(arr, id) {
    let tempIndex = -1;
    arr.find((item, index) => {
      if (item.id == id) {
        tempIndex = index;
        return true;
      }
    });
    return tempIndex;
  },
  // 阻止图片滑动冒泡
  stopTouchendBubble() {},
  onUnload: function () {
    subPub.off('orderModifyState', this.orderModifyStateId);
  },
  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {
    //调用刷新时将执行的方法
    this.onRefresh();
  },
  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {
    let { totalPage, pageNo } = this.data;
    if (totalPage <= pageNo) return;
    this.setData({
      pageNo: ++pageNo
    });
    this.getData();
  }
});
